import React, { useState } from 'react';
import { MenuFoldOutlined, MenuUnfoldOutlined } from '@ant-design/icons';
import { Input, Select, Collapse, Space, Spin, Divider } from 'antd';
import { ReactSortable } from 'react-sortablejs';

import { CatSource, tableSourceItem, CatItem } from './type';
import './index.css';
import user from '../../user.png';

const { Search } = Input;
const { Option } = Select;

//数据模型
const DataModel: React.FC<{ tableSource: tableSourceItem[]; onTablesourceChange: (id: number) => Promise<CatSource>; width?: number }> = ({
  tableSource,
  onTablesourceChange,
  width = 300,
}) => {
  const [loading, setLoading] = useState(false);
  const [isCollapse, setCollapse] = useState(false); //侧边栏开合
  const [keyword, setKeyword] = useState('');
  const [catSource, setCatSource] = useState<CatSource>({});

  /**
   * 选择数据源
   */
  function onChange(id: number) {
    setLoading(true);
    onTablesourceChange(id).then(res => {
      setCatSource(res);
      setTimeout(() => setLoading(false), 250);
    });
  }

  /** 渲染以及高亮
   * @param text 渲染的字符
   */
  function txtRender(text: string | undefined) {
    if (keyword && text && text.includes(keyword)) {
      const t = text.replace(keyword, `<span style="color:#1990FF">${keyword}</span>`);
      return <span dangerouslySetInnerHTML={{ __html: t }} />;
    }
    return <span>{text}</span>;
  }

  /** 纬度 / 度量 子项
   * @param data 数据源
   * @param title 标题
   */
  const Panel = (data: CatItem[] | undefined, title: string) => {
    const filtedData = keyword
      ? data?.filter(dimensionItem => dimensionItem.label?.includes(keyword) || dimensionItem.column?.includes(keyword))
      : data;

    const PanelItem = (filtedData || []).map(dimensionItem => (
      <div className="datamodel__dimension-item" key={dimensionItem.id} data-item={JSON.stringify(dimensionItem)}>
        <Space>
          <img src={user} height={20} />
          <span>{txtRender(dimensionItem.label)}</span>
        </Space>
      </div>
    ));

    return (
      <Collapse.Panel header={<div className="text-align-left">{title}</div>} key={title}>
        <div className="datamodel__Panel">
          {data?.length && (
            <ReactSortable
              list={filtedData || []}
              setList={() => void 0}
              group={{ name: 'shared', pull: 'clone', put: false }}
              children={PanelItem?.length ? PanelItem : keyword && <div className="null-content">没有符合的搜索结果</div>}
            />
          )}
        </div>
      </Collapse.Panel>
    );
  };

  return (
    <div className={`datamodel `} style={{ width: isCollapse ? '30px' : `${width}px` }}>
      {/* 伸缩按钮 */}
      <div className={`datamodel_collapse-btn ${isCollapse ? 'collapsed-btn' : ''}`} onClick={() => setCollapse(!isCollapse)}>
        {isCollapse ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
      </div>

      <div className={isCollapse ? 'collapsed-hidden' : 'collapsed-show'}>
        <div className="datamodel__header">
          <div className="datamodel__header-title">
            <h3 className="margin_0">数据模型</h3>
          </div>
          <Select
            showSearch
            placeholder="请选择数据源"
            onChange={onChange}
            className="width-percent-100"
            notFoundContent="没有符合的搜索结果"
            filterOption={(input, option) => option?.children?.toLowerCase().indexOf(input.toLowerCase()) >= 0}
          >
            {tableSource.map((tableItem, index) => {
              return (
                <Option value={tableItem?.id} key={index}>
                  {tableItem.table_name}
                </Option>
              );
            })}
          </Select>
        </div>
        {/* 搜索 */}
        <div className="datamodel__search">
          <Search placeholder="请输入搜索字段" allowClear onChange={e => setKeyword(e.target.value)} />
        </div>
        <div className="datamodel__dimension">
          <Spin spinning={loading}>
            <Collapse defaultActiveKey={['数据纬度', '度量']} expandIconPosition="right" ghost>
              {Panel(catSource.dimension_cols, '数据纬度')}
              <Divider />
              {Panel(catSource.measure_cols, '度量')}
            </Collapse>
          </Spin>
        </div>
      </div>
    </div>
  );
};

export default DataModel;
